package com.mobi.Survey.map;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.mobi.Survey.adapters.CustomAdapterUserList;
import com.mobi.Survey.lib.activities.AbstractScreen;
import com.mobi.Survey.lib.db.FavoriteTable;

public class UserListContainer extends Container implements
		SearchTask.SearchComplete {

	private ListView lvUserList;
	private View btnLoadMore;
	private CustomAdapterUserList adapter;
	private List<MapMarker> markers;

	private MapContainer mapContainer;
	private MapLogin mapLogin;

	public UserListContainer(AbstractScreen activity, MapContainer mapContainer) {
		this.activity = activity;
		this.mapLogin = (MapLogin) activity;
		lvUserList = (ListView) activity.findViewById(R.id.lvUserList);
		btnLoadMore = activity.findViewById(R.id.btnLoadMore);
		container = activity.findViewById(R.id.containerUsers);
		this.mapContainer = mapContainer;
	}

	public CustomAdapterUserList getAdapter() {
		return adapter;
	}

	@Override
	public void setupViews() {

		markers = MapLogin.getMapPoints();
		if (null == markers) {
			markers = new ArrayList<MapMarker>();

		}
		adapter = new CustomAdapterUserList(this.activity);

		adapter.setData(markers);
		lvUserList.setAdapter(adapter);
		lvUserList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> av, View view, int position,
					long id) {
				MapMarker mapMarker = markers.get(position);

				MapHelper.executeSurveyDownloadTask(activity, mapMarker);

			}
		});

		btnLoadMore.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View view) {

				SearchTask task = new SearchTask(
						UserListContainer.this.activity, mapLogin
								.getSerachContext());
				task.setSearchComplete(UserListContainer.this);
				task.execute();

			}
		});

	}

	public void refresh() {

		FavoriteTable table = new FavoriteTable(this.activity);
		Set<Long> favoriteSurveyIds = table.getAllFavoriteSurveyIds();
		table.closeDB();
		this.adapter.setFavoriteSurveys(favoriteSurveyIds);
		this.adapter.setData(MapLogin.getMapPoints());
		this.adapter.notifyDataSetChanged();
	}

	public View getBtnLoadMore() {
		return btnLoadMore;
	}

	public void setBtnLoadMore(View btnLoadMore) {
		this.btnLoadMore = btnLoadMore;
	}

	@Override
	public void onComplete(List<MapMarker> mapMarkers) {

		if (mapLogin.getSerachContext().startIndex == (mapLogin
				.getSerachContext().totaCount - 1)) {
			this.btnLoadMore.setVisibility(View.GONE);

		} else if (this.getBtnLoadMore().getVisibility() == View.GONE) {
			this.getBtnLoadMore().setVisibility(View.VISIBLE);
		}
		MapLogin.getMapPoints().addAll(mapMarkers);

		new SearchTask.IconDownloadTask().execute(adapter);

		mapContainer.refresh();
		this.refresh();
	}

}
